package org.mogu.adapter;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


import org.mogu.ContactManagerActivity;
import org.mogu.R;
import org.mogu.control.model.IMUser;
import org.mogu.db.ActiveUserHelper;
import org.mogu.db.DBhelper;
import org.mogu.service.InfoSync;
import org.mogu.staticvalue.Convert;
import org.mogu.tools.HeaderPic;
import org.mogu.tools.Imgtools;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

/*
 * 最近联系的数据适配器
 * @author androidSource@139.com
 * */
public class ChatListAdapter extends BaseAdapter 
		implements View.OnClickListener{
	ActiveUserHelper auh;
    SQLiteDatabase readdb;
    String code;
    String updating="（正在发送……）";
    
	//所属activity
	private Context mContext = null;
	
	//最近联系的数据数据
	public List<IMUser> recentContactV = new ArrayList<IMUser>();
	 
	 private int num=50;
	 private int page=0;
	 private int total=1;
	 
	private boolean isHistory=false;
	//加载布局文件的对象
	private LayoutInflater mLayoutInflater = null;	
	
	public SQLiteDatabase getReaddb() {
		if (readdb == null || !readdb.isOpen()) {
			readdb = auh.getReadableDatabase();
		}
		return readdb;
	}
 	public void close(){
 		if (readdb != null && readdb.isOpen()) {
			readdb.close();
		}
 	}
 	
	//构造函数
	public ChatListAdapter(Context paramContext,String code){
		 this.code=code;
		 auh=DBhelper.getDBHelper(paramContext);
		 mContext = paramContext;
		 mLayoutInflater = LayoutInflater.from(mContext);
		 
		 try {
			 getData();
			 //最近10个联系人
//			 this.notifyDataSetChanged();
			} catch (Exception e) {
				e.printStackTrace();
				
				return;
				// TODO: handle exception
			}
	}
	//构造函数
	public ChatListAdapter(Context paramContext,String code,boolean isHistory){
		this.code=code;
		this.isHistory=isHistory;
		auh=DBhelper.getDBHelper(paramContext);
		mContext = paramContext;
		mLayoutInflater = LayoutInflater.from(mContext);
		
		try {
			getData();
			//最近10个联系人
//			 this.notifyDataSetChanged();
		} catch (Exception e) {
			e.printStackTrace();
			
			return;
			// TODO: handle exception
		}
	}
	 
	public void getData(){
		getData(0);
	}
	public void getData(int page){
		this.page=page;
		 String[] imUserArr={Convert.uname,code};
		 recentContactV.clear();
		 IMUser imUser;
		 int contentid=0;

		 synchronized (InfoSync.class) {
			 Cursor userCursor;
			
			userCursor = getReaddb()
						.rawQuery(
								"select code,title,content,replyType,maincode,level,father,lastUpdateTime,id from content where username=? and father=? order by lastUpdateTime desc",
								imUserArr);
			 
			 userCursor.moveToFirst();
			 int i=0;
			 total=0;
			 while(!userCursor.isAfterLast()){
				 total++;
				 if(contentid==0||contentid<userCursor.getInt(8)){
					 contentid=userCursor.getInt(8);
				 }
				 
				 if(page==total/num&&i<num){
					 imUser=new IMUser();
					 imUser.setCode(userCursor.getString(0));
					 imUser.setTitle(userCursor.getString(1));
					 imUser.setContent(userCursor.getString(2));
					 imUser.setReplyType(userCursor.getString(3));
					 imUser.setMaincode(userCursor.getString(4));
					 imUser.setLevel(userCursor.getString(5));
					 imUser.setFather(userCursor.getString(6));
					 imUser.setLastUpdateTime(userCursor.getString(7));
					 recentContactV.add(imUser);
					 
					 i+=1;
				 }else{
					 if(!this.isHistory){
						 break;
					 }
				 }
				 
				 userCursor.moveToNext();
			 }
			 userCursor.close();
			 close();
			 
			 if(!this.isHistory){
				 ContentValues activeuser = new ContentValues();
				 String[] whereArgs={code,Convert.uname};
					activeuser.put("contentid", String.valueOf(contentid));
					int num=auh.getWritableDatabase().update("contentread", activeuser, "code=? and username=?", whereArgs);
					if(num==0){
						activeuser.put("code", code);
						activeuser.put("username", Convert.uname);
						auh.getWritableDatabase().insert("contentread", null, activeuser);
					} 
			 }
			 
		 }
		 Collections.reverse(recentContactV);
		 this.notifyDataSetChanged();
	 }
	
	/*
	 * 获得list的列表项总数
	 * */
	public int getCount(){
	    return recentContactV.size();
	}
	/*
	 * 获得list的列表项总页数
	 * */
	public int getCountPage(){
		int page=total/num;
		if(total%num>0){
			page++;
		}
		return page;
	}
	
	public int getCurrentPage(){
		return getCountPage()-page;
	}

	/*
	 * 获得list的列表项
	 * */
	public Object getItem(int paramInt){
		 return recentContactV.get(paramInt);
	}

	/*
	 * 获得list的列表项下标
	 * */
	public long getItemId(int paramInt){
	    return paramInt;
	}

	/*
	 * 列表项的视图函数
	 * */
	public View getView(int paramInt, View paramView, ViewGroup paramViewGroup){
		System.out.println("getView");
		
		View localView = paramView;
		//判断当前view视图参数是否为null
	    if (localView == null){
	        //加载一级视图的布局文件
	    	localView = mLayoutInflater.inflate(R.layout.chat_item, null);
	    }
	    /*
	     * 相关控件设置
	     * */
	    IMUser imUser=(IMUser)getItem(paramInt);
	    
	    //头像
	    ImageView chaterror = (ImageView)localView.findViewById(R.id.chaterror);
//	    //在线标识
//	    ImageView buddyStatue = (ImageView)localView.findViewById(R.id.recent_buddyStatue);
	    //昵称
	    TextView name = (TextView)localView.findViewById(R.id.umeng_analyse_atomtxt);
	    //心情
	    TextView info = (TextView)localView.findViewById(R.id.umeng_analyse_stateOrTime);
	    RelativeLayout backgroup=(RelativeLayout)localView.findViewById(R.id.umeng_analyse_bubble);
	    View r=(View)localView.findViewById(R.id.umeng_analyse_atom_left_margin);
	    r.setVisibility(View.VISIBLE);
	    View l=(View)localView.findViewById(R.id.umeng_analyse_atom_right_margin);
	    l.setVisibility(View.VISIBLE);
	    if(!"0".equals(imUser.getTitle())&&!"-1".equals(imUser.getTitle())&&!"-2".equals(imUser.getTitle())){
	    	backgroup.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.umeng_analyse_user_bubble));
	    	r.setVisibility(View.GONE);
	    }else{
	    	backgroup.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.umeng_analyse_dev_bubble));
	    	l.setVisibility(View.GONE);
	    }
	    if("-1".equals(imUser.getTitle())){
	    	chaterror.setVisibility(View.VISIBLE);
	    }else{
	    	chaterror.setVisibility(View.GONE);
	    }
	    
	    //编辑按钮
//	    ImageView contextbtn = (ImageView)localView.findViewById(R.id.recent_contextbtn);
	    //设置编辑按钮的单击事件监听器
//	    contextbtn.setOnClickListener(this);
	    
	    
	    /*
	     * 设置控件内容
	     * */
//    	TreeNode childItem = (TreeNode)recentContactV.get(paramInt);
	    name.setText(Imgtools.getContent(imUser.getContent(),name));
	    
//	    if("-2".equals(imUser.getTitle())){
//	    	name.setText(Imgtools.getContent(imUser.getContent()+updating,name));
////	    	info.setText("正在发送中");
//	    	name.setTextColor(0xFF228B22);
//	    }else{
//	    	
//	    	name.setTextColor(0xFF6F6F6F);
//	    }
	    info.setText(imUser.getLastUpdateTime().subSequence(0, 19));
    	
//	    headIcon.setImageResource(HeaderPic.getHeader(imUser.getHeader()));
//	    	buddyStatue.setImageResource(R.drawable.status_offline);
	    
//	    //设置视图间距
//	    localView.setPadding(0, 0, 0, 0);
//	    //获取资源文件对象
//	    Drawable localDrawable = mContext.getResources().getDrawable(R.drawable.highlight_item);
//	    //设置视图背景
//	    localView.setBackgroundDrawable(localDrawable);
	    
	    
	    return localView;
	}
	
	/*
	 * 控件单击事件监听器函数
	 * */
	@Override
	public void onClick(View view){
		Intent mIntent = new Intent(mContext, ContactManagerActivity.class);
		mContext.startActivity(mIntent);
	}
  
}
